<template>
  <div class="">
    <MyTable :list="goodList">
      <!-- 为 组件的 head插槽 传标签 -->
      <template #head>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>

      <!-- 为 组件的 tr插槽 传标签，且 通过 变量row 接收 组件传来的 good数据 -->
      <template #tr="row">
        <td>{{ row.good.id }}</td>
        <td>{{ row.good.goods_name }}</td>
        <td>{{ row.good.goods_price }}</td>
        <td>
          <!-- 新增tab 输入框和按钮 -->
          <input
            v-if="row.good.inputVisible"
            type="text"
            class="form-control"
            placeholder="新tag"
            v-focus
            v-model.trim="row.good.inputValue"
            @keyup.enter="addTag(row.good)"
            @blur="row.good.inputVisible = false"
          />

          <button
            v-else
            @click="row.good.inputVisible = true"
            type="button"
            class="btn btn-primary"
          >
            +Tag
          </button>

          <span
            class="badge bg-warning text-dark kaidian"
            v-for="(tag, i) in row.good.tags"
            :key="i"
            >{{ tag }}</span
          >
        </td>
        <td>
          <button
            type="button"
            class="btn btn-danger btn-sm"
            @click="doDel(row.good.id)"
          >
            删
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from "../components/MyTable.vue";

export default {
  name: "",
  props: {},
  data() {
    return {
      goodList: [],
    };
  },
  // vue的 入口函数
  async created() {
    const { data: res } = await this.$axios({
      methods: "get",
      url: "/api/goods",
    });

    console.log(res);
    this.goodList = res.data;
  },
  methods: {
    addTag(good) {
      // 0.为空判断
      if (good.inputValue.length === 0) return;
      // 1.将 文本框内容 加入到 商品的 tags 数组
      good.tags.push(good.inputValue);
      // 2.清空文本框
      good.inputValue = "";
      // 3.切换按钮和文本框显示
      good.inputVisible = false;
    },
  },
  computed: {},
  watch: {},
  components: { MyTable },
};
</script>

<style lang="less" scoped>
.kaidian {
  margin-right: 5px;
}
</style>
